<template>
  <div class="repository-commits-container">
    <div class="page-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="page-info">
          <h1>提交记录</h1>
          <p>{{ repository.name }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-select v-model="currentBranch" placeholder="选择分支" @change="loadCommits">
          <el-option 
            v-for="branch in branches"
            :key="branch.name"
            :label="branch.name"
            :value="branch.name"
          />
        </el-select>
      </div>
    </div>

    <div class="commits-content">
      <el-card>
        <div class="commits-list">
          <div 
            v-for="commit in commits"
            :key="commit.id"
            class="commit-item"
            @click="viewCommit(commit)"
          >
            <div class="commit-info">
              <div class="commit-header">
                <div class="commit-message">
                  <el-icon><Commit /></el-icon>
                  {{ commit.message }}
                </div>
                <div class="commit-actions">
                  <el-button size="small" @click.stop="viewCommit(commit)">查看</el-button>
                  <el-dropdown @command="handleCommitAction">
                    <el-button size="small" @click.stop>
                      更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{action: 'cherry-pick', commit}">Cherry-pick</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'revert', commit}">回滚</el-dropdown-item>
                        <el-dropdown-item :command="{action: 'browse', commit}">浏览代码</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
              
              <div class="commit-details">
                <div class="commit-meta">
                  <div class="author-info">
                    <el-avatar :src="commit.authorAvatar" :size="32" />
                    <div class="author-details">
                      <div class="author-name">{{ commit.author }}</div>
                      <div class="commit-time">{{ formatTime(commit.time) }}</div>
                    </div>
                  </div>
                  
                  <div class="commit-hash">
                    <span class="hash-text">{{ commit.hash.substring(0, 8) }}</span>
                    <el-button size="small" type="text" @click.stop="copyHash(commit.hash)">
                      <el-icon><CopyDocument /></el-icon>
                    </el-button>
                  </div>
                </div>
                
                <div class="commit-stats" v-if="commit.stats">
                  <div class="file-changes">
                    <span class="changed-files">
                      <el-icon><Document /></el-icon>
                      {{ commit.stats.changedFiles }} 个文件
                    </span>
                    <span class="additions" v-if="commit.stats.additions > 0">
                      +{{ commit.stats.additions }}
                    </span>
                    <span class="deletions" v-if="commit.stats.deletions > 0">
                      -{{ commit.stats.deletions }}
                    </span>
                  </div>
                  
                  <div class="change-bar" v-if="commit.stats.additions || commit.stats.deletions">
                    <div 
                      class="additions-bar"
                      :style="{ width: getAdditionsPercentage(commit.stats) + '%' }"
                    ></div>
                    <div 
                      class="deletions-bar"
                      :style="{ width: getDeletionsPercentage(commit.stats) + '%' }"
                    ></div>
                  </div>
                </div>
              </div>
              
              <div class="commit-files" v-if="expandedCommit === commit.id">
                <div class="files-header">
                  <span>变更文件</span>
                  <el-button size="small" type="text" @click.stop="expandedCommit = null">
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
                <div class="files-list">
                  <div 
                    v-for="file in commit.files"
                    :key="file.path"
                    class="file-item"
                  >
                    <div class="file-info">
                      <el-icon class="file-icon" :class="getFileStatusClass(file.status)">
                        <component :is="getFileStatusIcon(file.status)" />
                      </el-icon>
                      <span class="file-path">{{ file.path }}</span>
                    </div>
                    <div class="file-stats">
                      <span class="additions" v-if="file.additions > 0">+{{ file.additions }}</span>
                      <span class="deletions" v-if="file.deletions > 0">-{{ file.deletions }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="total"
            :page-sizes="[20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadCommits(true)"
            @current-change="loadCommits(false)"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getRepositoryDetail,
  getRepositoryBranches,
  getRepositoryCommits
} from '@/api/version'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const repository = ref({})
const branches = ref([])
const commits = ref([])
const currentBranch = ref('main')
const expandedCommit = ref(null)
const total = ref(0)

// 分页参数
const pagination = reactive({
  page: 1,
  size: 20
})

// 页面加载
onMounted(async () => {
  await loadRepository()
  await loadBranches()
  await loadCommits()
})

// 加载仓库信息
const loadRepository = async () => {
  try {
    const response = await getRepositoryDetail(route.params.id)
    if (response.code === 200) {
      repository.value = response.data
    }
  } catch (error) {
    console.error('获取仓库信息失败:', error)
    ElMessage.error('获取仓库信息失败')
  }
}

// 加载分支列表
const loadBranches = async () => {
  try {
    const response = await getRepositoryBranches(route.params.id)
    if (response.code === 200) {
      branches.value = response.data || []
      if (branches.value.length > 0) {
        currentBranch.value = branches.value.find(b => b.isDefault)?.name || branches.value[0].name
      }
    }
  } catch (error) {
    console.error('获取分支列表失败:', error)
  }
}

// 加载提交记录
const loadCommits = async (reset = false) => {
  if (reset) {
    pagination.page = 1
  }
  
  try {
    const response = await getRepositoryCommits(route.params.id, {
      branch: currentBranch.value,
      page: pagination.page,
      size: pagination.size
    })
    if (response.code === 200) {
      commits.value = response.data.records || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取提交记录失败:', error)
    ElMessage.error('获取提交记录失败')
  }
}

// 查看提交详情
const viewCommit = (commit) => {
  if (expandedCommit.value === commit.id) {
    expandedCommit.value = null
  } else {
    expandedCommit.value = commit.id
    // 如果没有文件信息，可以在这里加载
    if (!commit.files) {
      loadCommitFiles(commit)
    }
  }
}

// 加载提交文件变更
const loadCommitFiles = async (commit) => {
  try {
    // 这里应该调用获取提交文件变更的API
    // const response = await getCommitFiles(commit.id)
    // commit.files = response.data
  } catch (error) {
    console.error('获取提交文件失败:', error)
  }
}

// 处理提交操作
const handleCommitAction = ({ action, commit }) => {
  switch (action) {
    case 'cherry-pick':
      cherryPickCommit(commit)
      break
    case 'revert':
      revertCommit(commit)
      break
    case 'browse':
      browseCommit(commit)
      break
  }
}

// Cherry-pick 提交
const cherryPickCommit = (commit) => {
  ElMessage.info('Cherry-pick 功能开发中...')
}

// 回滚提交
const revertCommit = (commit) => {
  ElMessage.info('回滚功能开发中...')
}

// 浏览提交代码
const browseCommit = (commit) => {
  router.push(`/version/repository/${route.params.id}/commit/${commit.hash}`)
}

// 复制哈希值
const copyHash = (hash) => {
  navigator.clipboard.writeText(hash).then(() => {
    ElMessage.success('哈希值已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 获取文件状态图标
const getFileStatusIcon = (status) => {
  const iconMap = {
    'added': 'Plus',
    'modified': 'Edit',
    'deleted': 'Minus',
    'renamed': 'Right'
  }
  return iconMap[status] || 'Document'
}

// 获取文件状态样式类
const getFileStatusClass = (status) => {
  return `status-${status}`
}

// 获取新增行百分比
const getAdditionsPercentage = (stats) => {
  const total = stats.additions + stats.deletions
  return total > 0 ? (stats.additions / total) * 100 : 0
}

// 获取删除行百分比
const getDeletionsPercentage = (stats) => {
  const total = stats.additions + stats.deletions
  return total > 0 ? (stats.deletions / total) * 100 : 0
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.repository-commits-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .page-info {
      h1 {
        font-size: 24px;
        font-weight: 600;
        margin: 0 0 4px 0;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.commits-content {
  max-width: 1000px;
  margin: 0 auto;
}

.commits-list {
  .commit-item {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.3s;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:hover {
      background-color: #f8f9fa;
    }
    
    .commit-info {
      .commit-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        .commit-message {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          flex: 1;
        }
        
        .commit-actions {
          display: flex;
          gap: 8px;
        }
      }
      
      .commit-details {
        .commit-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          
          .author-info {
            display: flex;
            align-items: center;
            gap: 12px;
            
            .author-details {
              .author-name {
                font-weight: 500;
                color: #303133;
                margin-bottom: 4px;
              }
              
              .commit-time {
                color: #909399;
                font-size: 12px;
              }
            }
          }
          
          .commit-hash {
            display: flex;
            align-items: center;
            gap: 4px;
            
            .hash-text {
              font-family: monospace;
              background-color: #f5f5f5;
              padding: 4px 8px;
              border-radius: 3px;
              color: #606266;
            }
          }
        }
        
        .commit-stats {
          .file-changes {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 8px;
            
            .changed-files {
              display: flex;
              align-items: center;
              gap: 4px;
              color: #606266;
            }
            
            .additions {
              color: #67c23a;
              font-weight: 500;
            }
            
            .deletions {
              color: #f56c6c;
              font-weight: 500;
            }
          }
          
          .change-bar {
            height: 4px;
            background-color: #e4e7ed;
            border-radius: 2px;
            overflow: hidden;
            display: flex;
            
            .additions-bar {
              background-color: #67c23a;
            }
            
            .deletions-bar {
              background-color: #f56c6c;
            }
          }
        }
      }
      
      .commit-files {
        margin-top: 16px;
        border-top: 1px solid #f0f0f0;
        padding-top: 16px;
        
        .files-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          font-weight: 500;
          color: #303133;
        }
        
        .files-list {
          .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            
            .file-info {
              display: flex;
              align-items: center;
              gap: 8px;
              
              .file-icon {
                &.status-added {
                  color: #67c23a;
                }
                
                &.status-modified {
                  color: #e6a23c;
                }
                
                &.status-deleted {
                  color: #f56c6c;
                }
                
                &.status-renamed {
                  color: #409eff;
                }
              }
              
              .file-path {
                font-family: monospace;
                color: #606266;
              }
            }
            
            .file-stats {
              display: flex;
              gap: 8px;
              
              .additions {
                color: #67c23a;
              }
              
              .deletions {
                color: #f56c6c;
              }
            }
          }
        }
      }
    }
  }
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

@media (max-width: 768px) {
  .repository-commits-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    padding: 20px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .commit-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .commit-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .file-changes {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
